﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Service.Device.Dto;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace Admin.NET.Application;

/// <summary>
/// 人脸设备服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class DeviceService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Device> _deviceRep;
    private readonly IClientWebSocketManager _clientWebSocketManager;
    private readonly IPlatFormJobManager platFormJobManager;

    public DeviceService(SqlSugarRepository<Device> deviceRep, IClientWebSocketManager clientWebSocketManager, IPlatFormJobManager platFormJobManager)
    {
        _deviceRep = deviceRep;
        _clientWebSocketManager = clientWebSocketManager;
        this.platFormJobManager = platFormJobManager;
    }

#region 一般功能

    /// <summary>
    /// 分页查询人脸设备
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询人脸设备")]
    public async Task<SqlSugarPagedList<DeviceOutput>> Page(PageDeviceInput input)
    {
        var onlineDeviceSnList = _clientWebSocketManager.SelectAllConnections().Keys.ToList();
        var onlinePlatDeptList = platFormJobManager.SelectAllDevices().Keys.ToList();

        input.SearchKey = input.SearchKey?.Trim();
        var query = _deviceRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Name.Contains(input.SearchKey)
                || u.ClientSn.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ClientSn), u => u.ClientSn.Contains(input.ClientSn.Trim()))
            .WhereIF(input.ProjectId>0, u => u.ProjectId == input.ProjectId)
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Project>((u, projectid) => u.ProjectId == projectid.Id )
            .Select((u, projectid) => new DeviceOutput
            {
                Id = u.Id,
                Name = u.Name,
                ClientSn = u.ClientSn,
                Direction = u.Direction,
                ProjectId = u.ProjectId, 
                ProjectIdName = projectid.Name,
                DeviceConnect = u.DeviceConnect,
                DeviceModel = u.DeviceModel,
                EnableEmpSend = u.EnableEmpSend,
                EnableRecLog = u.EnableRecLog,
                EnableUploadLog = u.EnableUploadLog,
                EnableRecNotMatchUploadLog = u.EnableRecNotMatchUploadLog,
                IsOnline = onlineDeviceSnList.Contains(u.ClientSn),
                IsOnlineServer = onlinePlatDeptList.Contains(u.ClientSn),
                Status = (StatusEnum)u.Status,
                TenantId = u.TenantId,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                //CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                EnableGetEmpInfo = u.EnableGetEmpInfo,
            });
		//return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加人脸设备
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加人脸设备")]
    public async Task<long> Add(AddDeviceInput input)
    {
        var entity = input.Adapt<Device>();
        await _deviceRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除人脸设备
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除人脸设备")]
    public async Task Delete(DeleteDeviceInput input)
    {
        var entity = await _deviceRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deviceRep.FakeDeleteAsync(entity);   //假删除
        //await _deviceRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新人脸设备
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新人脸设备")]
    public async Task Update(UpdateDeviceInput input)
    {
        var entity = input.Adapt<Device>();
        await _deviceRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取人脸设备
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取人脸设备")]
    public async Task<Device> Detail([FromQuery] QueryByIdDeviceInput input)
    {
        return await _deviceRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取人脸设备列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取人脸设备列表")]
    public async Task<List<DeviceOutput>> List([FromQuery] PageDeviceInput input)
    {
        return await _deviceRep.AsQueryable().Select<DeviceOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取项目ID列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "ProjectProjectIdDropdown"), HttpGet]
    [DisplayName("获取项目ID列表")]
    public async Task<dynamic> ProjectProjectIdDropdown()
    {
        return await _deviceRep.Context.Queryable<Project>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    #endregion

    #region  设备命令
    /// <summary>
    /// 获取在线设备列表
    /// </summary>
    [HttpGet]
    [ApiDescriptionSettings(Name = "cmd_GetOnlineClient", Order = 1000)]
    [DisplayName("获取在线设备")]
    public List<string> cmd_GetOnlineClient()
    {
        return _clientWebSocketManager.SelectAllConnections().Select(u => u.Key).ToList();
    }


    /// <summary>
    /// 重启设备
    /// </summary>
    /// <param name="DeviceSn"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "cmd_Restart", Order = 999)]
    [DisplayName("重启设备")]
    public async Task<CommonClientResult> cmd_Restart([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "reboot",
            command_id = CommandId,
        };
        return await SendObjectMsg(DeviceSn, Message);
    }


    /// <summary>
    /// 获取设备版本信息
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_Getversion")]
    [ApiDescriptionSettings(Name = "cmd_Getversion", Order = 998)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_Getversion([FromBody]  string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "get version",
            command_id = CommandId,
        };
        return await SendObjectMsg(DeviceSn, Message);
    }

    /// <summary>
    /// 获取所有人员ID
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_GetAllpersonid")]
    [ApiDescriptionSettings(Name = "cmd_GetAllpersonid", Order = 997)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_GetAllpersonid([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "get allpersonid",
        };
        var result = await SendObjectMsg(DeviceSn, Message);
        return result;
    }

    /// <summary>
    /// 设备截图
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_Snapshot")]
    [ApiDescriptionSettings(Name = "cmd_Snapshot", Order = 996)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_Snapshot([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "snapshot",
        };
        return await SendObjectMsg(DeviceSn, Message);
    }

    /// <summary>
    /// 按ID删除人员
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_DeletePerson")]
    [ApiDescriptionSettings(Name = "cmd_DeletePerson", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_DeletePerson(DeletePersonRequest input)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "delete person(s)",
            flag = -1,
            id = input.Id,
        };
        return await SendObjectMsg(input.DeviceSn, Message);
    }

    /// <summary>
    /// 删除所有人员
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_DeleteAllPerson")]
    [ApiDescriptionSettings(Name = "cmd_DeleteAllPerson", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_DeleteAllPerson([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "delete person(s)",
            flag = 3,
            id = "",
        };
        return await SendObjectMsg(DeviceSn, Message);
    }

    /// <summary>
    /// 获取应用参数
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_RequestAppParams")]
    [ApiDescriptionSettings(Name = "cmd_RequestAppParams", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_RequestAppParams([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "request app params",
        };
        return await SendObjectMsg(DeviceSn, Message);
    }


    /// <summary>
    /// 常用参数设置
    /// </summary>
    /// <returns></returns>
    [HttpPost("cmd_UpdateAppParams")]
    [ApiDescriptionSettings(Name = "cmd_UpdateAppParams", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> cmd_UpdateAppParams(UpdateAppParamsRequest request)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "update app params",
            //face = new
            //{
            //    alive_level = 1,  //活体检测等级 1:弱等级 2:强等级
            //    derep_timeout = 3,  //重复超时。取值范围：3~60。（去除重复开关为true时存在）
            //    enable_alive = false,  //活体检测开关
            //    enable_dereplication = true,  //去除重复开关。true：开 false：关。
            //    enable_match = true,  //比对开关。true：开 false：关。
            //    enable_same_face_reg = true, //是否允许相同人脸重复注册
            //    match_score = 80,  //确信分数。取值范围：70~100。（比对开关为true时存在）
            //    pic_form = "closeup",   //图像输出形式。overall：全景 closeup：特写 both：全景+特写 none：无图。
            //    output_not_matched = true,  //是否输出对比失败图像,输出不匹配人脸。true：输出 false：不输出。（比对开关为true时存在）
            //    quality = 70,  //输出图像质量。取值范围：0~100
            //}
            face = new
            {
                alive_level = request.face.alive_level,
                derep_timeout = request.face.derep_timeout,
                enable_alive = request.face.enable_alive,
                enable_dereplication = request.face.enable_dereplication,
                enable_match = request.face.enable_match,
                enable_same_face_reg = request.face.enable_same_face_reg,
                match_score = request.face.match_score,
                pic_form = request.face.pic_form,
                output_not_matched = request.face.output_not_matched,
                quality = request.face.quality,
            }
        };
        return await SendObjectMsg(request.DeviceSn, Message);
    }

    /// <summary>
    /// 开启采集
    /// </summary>
    /// <returns></returns>
    [HttpPost("OpenCJ")]
    [ApiDescriptionSettings(Name = "OpenCJ", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> OpenCJ([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "update app params",
            face = new
            {
                alive_level = 1,  //活体检测等级 1:弱等级 2:强等级
                derep_timeout = 3,  //重复超时。取值范围：3~60。（去除重复开关为true时存在）
                enable_alive = false,  //活体检测开关
                enable_dereplication = true,  //去除重复开关。true：开 false：关。
                enable_match = true,  //比对开关。true：开 false：关。
                enable_same_face_reg = true, //是否允许相同人脸重复注册
                match_score = 80,  //确信分数。取值范围：70~100。（比对开关为true时存在）
                pic_form = "closeup",   //图像输出形式。overall：全景 closeup：特写 both：全景+特写 none：无图。
                output_not_matched = true,  //是否输出对比失败图像,输出不匹配人脸。true：输出 false：不输出。（比对开关为true时存在）
                quality = 70,  //输出图像质量。取值范围：0~100
            }
        };
        return await SendObjectMsg(DeviceSn, Message);
    }

    /// <summary>
    /// 关闭采集
    /// </summary>
    /// <returns></returns>
    [HttpPost("CloseCJ")]
    [ApiDescriptionSettings(Name = "CloseCJ", Order = 995)]
    [AllowAnonymous]
    public async Task<CommonClientResult> CloseCJ([FromBody] string DeviceSn)
    {
        string CommandId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
        var Message = new
        {
            cmd = "update app params",
            face = new
            {
                alive_level = 1,  //活体检测等级 1:弱等级 2:强等级
                derep_timeout = 3,  //重复超时。取值范围：3~60。（去除重复开关为true时存在）
                enable_alive = false,  //活体检测开关
                enable_dereplication = true,  //去除重复开关。true：开 false：关。
                enable_match = true,  //比对开关。true：开 false：关。
                enable_same_face_reg = true, //是否允许相同人脸重复注册
                match_score = 80,  //确信分数。取值范围：70~100。（比对开关为true时存在）
                pic_form = "closeup",   //图像输出形式。overall：全景 closeup：特写 both：全景+特写 none：无图。
                output_not_matched = true,  //是否输出对比失败图像,输出不匹配人脸。true：输出 false：不输出。（比对开关为true时存在）
                quality = 70,  //输出图像质量。取值范围：0~100
            }
        };
        return await SendObjectMsg(DeviceSn, Message);
    }


    private async Task<CommonClientResult> SendObjectMsg([FromBody] string DeviceSn, [FromBody] Object Msg)
    {
        if (Msg == null) return new CommonClientResult() { code = ResponseCode.Other, msg = "发送数据不能为空。" };
        if (string.IsNullOrEmpty(DeviceSn)) return new CommonClientResult() { code = ResponseCode.Other, msg = "设备号不能为空。" }; ;
        if (string.IsNullOrEmpty(JsonConvert.SerializeObject(Msg))) return new CommonClientResult() { code = ResponseCode.Other, msg = "发送数据不能为空。" };
        var _connections = _clientWebSocketManager.SelectAllConnections();
        //查_connections 的key中是否存在DeviceSn
        if (!_connections.ContainsKey(DeviceSn)) new CommonClientResult() { code = ResponseCode.AvailableOrClosed, msg = "连接不可用或已关闭连接不可用或已关闭。" };

        var DeleteResponse =
        await _clientWebSocketManager
            .SendAndWaitForResponseAsync(DeviceSn, JsonConvert.SerializeObject(Msg), TimeSpan.FromSeconds(10));
        return DeleteResponse;
    }
    #endregion


}

public class DeletePersonRequest
{
    public string DeviceSn { get; set; }
    public string Id { get; set; }
}

public class UpdateAppParamsRequest
{
    public string DeviceSn { get; set; }
    public FaceParams face { get; set; }
}

public class FaceParams
{
    public int alive_level { get; set; } // 活体检测等级  
    public int derep_timeout { get; set; } // 重复超时  
    public bool enable_alive { get; set; } // 活体检测开关  
    public bool enable_dereplication { get; set; } // 去除重复开关  
    public bool enable_match { get; set; } // 比对开关  
    public bool enable_same_face_reg { get; set; } // 是否允许相同人脸重复注册  
    public int match_score { get; set; } // 确信分数  
    public string pic_form { get; set; } // 图像输出形式  
    public bool output_not_matched { get; set; } // 是否输出对比失败图像  
    public int quality { get; set; } // 输出图像质量  
}